using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.DirectoryServices.AccountManagement;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;
using Microsoft.SharePoint.WebPartPages;

namespace zevenseas.Community.Web.UI.WebControls.WebParts
{
    /// <summary>
    ///     ChangePasswordNET3
    /// </summary>
    public class ChangePasswordNET35 : System.Web.UI.WebControls.WebParts.WebPart, IWebEditable
    {
        #region Private properties

        private TextBox oldpassword;
        private TextBox newpassword;
        private TextBox checknewpassword;
        private LinkButton btn;
        private Label output;

        private string domain;
        
        #endregion Private properties

        #region Public properties
        [WebBrowsable(false), WebDisplayName("Domain")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("ChangePassword Settings")]
        [DefaultValue("")]
        public string Domain
        {
            get { return domain; }
            set
            {
                domain = value;
            }
        }
       
              
        #endregion Public properties

        #region Protected properties

        #endregion Protected properties

        #region  Public methods

        #endregion Public methods

        #region Protected methods

        protected string GetToolPaneLink()
        {
            bool hasRights = ((ISecurableObject)SPContext.Current.Web).DoesUserHavePermissions((SPBasePermissions)Microsoft.SharePoint.SPPermissionGroup.WebDesigner);

            if (!hasRights)
                return "Web Part has not been configured";

            string editLink = ToolPane.GetShowExtensibleToolPaneEvent(string.Format(@"'{0}'", this.UniqueID));
            editLink = string.Format(@"javascript:{0}", editLink.Replace(@"ExtensibleView", @"Edit"));
            return editLink;
        } 

        protected override void CreateChildControls()
        {
            //this.Title = "ChangePassword .NET 3.5";

            this.oldpassword = new TextBox();
            this.oldpassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(oldpassword);

            this.newpassword = new TextBox();
            this.newpassword.ID = "newpassword";
            this.newpassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(newpassword);

            this.checknewpassword = new TextBox();
            this.checknewpassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(checknewpassword);                      

            this.btn = new LinkButton();
            this.btn.Click += new EventHandler(btn_Click);
            this.btn.Text = "Change Password";
            this.Controls.Add(btn);

            this.output = new Label();
            this.Controls.Add(output);

            base.CreateChildControls();
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (string.IsNullOrEmpty(domain))
            {
                Literal configWebPart = new Literal();
                configWebPart.Text = "To configure this web part, <a href=" + GetToolPaneLink() +
                                     ">open the tool pane</a> and then configure the domain settings";
                configWebPart.RenderControl(writer);
                return;
            }

            else
            {
                string strLoginName = string.Empty;

                try
                {
                    SPWeb webContext = SPControl.GetContextWeb(Context);
                    strLoginName = webContext.CurrentUser.LoginName;
                }
                catch (Exception)
                {
                    output.Text += "<BR> Please sign in first using the 'Sign In' button above";
                }
                
                //I know, i know.. i need to do this properly ;)
                if (strLoginName != string.Empty)
                {
                    writer.Write("<table border=0>");
                    writer.Write("<tr>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("Current password:");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    oldpassword.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("</tr>");
                    writer.Write("<tr valign='top'>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("New password:");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    newpassword.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("</tr>");
                    writer.Write("<tr valign='top'>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("Confirm new password:");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    checknewpassword.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</tr>");
                    writer.Write("<tr valign='top'>");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    btn.RenderControl(writer);
                    writer.Write("</td>");
                    writer.Write("<td class='ms-vb'>");
                    writer.Write("</td>");
                    writer.Write("</tr>");
                    writer.Write("</table>");

                    output.RenderControl(writer);
                }
                else { output.RenderControl(writer); }
            }

        }

        #endregion Protected methods

        #region Private methods

        #endregion Private methods

        #region Events
        
        void btn_Click(object sender, EventArgs e)
        {
            output.Text = string.Empty;
            SPWeb webContext = SPControl.GetContextWeb(Context);
            string strLoginName = webContext.CurrentUser.LoginName;
            int iPosition = strLoginName.IndexOf("\\") + 1;
            strLoginName = strLoginName.Substring(iPosition);

            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain);

                // Create an in-memory user object to use as the query example.
                UserPrincipal u = new UserPrincipal(ctx);
                // Set properties on the user principal object.
                u.SamAccountName = strLoginName;
                // Create a PrincipalSearcher object to perform the search.
                PrincipalSearcher ps = new PrincipalSearcher();
                ps.QueryFilter = u;

                UserPrincipal _user = (UserPrincipal)ps.FindOne();

                try
                {
                    _user.ChangePassword(oldpassword.Text.ToString(), newpassword.Text.ToString());
                    output.Text += "<BR><B>Password changed</B>";
                }
                catch (Exception changePasswordError)
                {
                    output.Text += "<BR>" + changePasswordError.InnerException.Message.ToString();
                }
            }
            catch (Exception adError)
            {
                output.Text += "<BR>" + adError.Message.ToString();
            }

        }


        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();

            EditorPart changePasswordEditor = new ChangePassword35Editor();
            changePasswordEditor.ID = "changePasswordEditor" + this.ID;

            editors.Add(changePasswordEditor);
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }
        #endregion Events

    }
}
